package tacos.domain;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;

import javax.persistence.*;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Data
@Entity
@Table(name = "Taco_Order")  // 表名Order实体应该持久化到Taco_Order表中
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
public class Order implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private Date placedAt;

    @ManyToOne(fetch = FetchType.LAZY)  // 使用懒加载的模式，默认不是
    @JoinColumn(name = "user")
    private User user;

    @NotBlank(message = "Name is required")
    @Column(name = "name")
    private String deliveryName;
    @NotBlank(message = "Street is required")
    @Column(name = "street")
    private String deliveryStreet;
    @NotBlank(message = "City is required")
    @Column(name = "city")
    private String deliveryCity;
    @NotBlank(message = "State is required")
    @Size(max = 2,message = "State's max length is 2")
    @Column(name = "state")
    private String deliveryState;
    @NotBlank(message = "Zip is required")
    @Column(name = "zip")
    private String deliveryZip;
    private String ccNumber;
    @Pattern(regexp = "^(0[1-9]|1[0-2])([\\/])([1-9][0-9])$")
    private String ccExpiration;
    @Digits(integer = 3, fraction = 0, message = "Invalid CVV")  // 三位数字，小数点后0位
    private String ccCVV;

    @ManyToMany(targetEntity = Taco.class)
    @JoinTable(name = "Taco_order_tacos",
            joinColumns = @JoinColumn(name = "tacoOrder"),
            inverseJoinColumns = @JoinColumn(name = "taco")
    )
    private List<Taco> tacos = new ArrayList<>();

    @PrePersist
    void placedAt() {
        this.placedAt = new Date();
    }


    public void addDesign(Taco design){
        this.tacos.add(design);
    }
}
